package com.zhenwei.zscm.repo;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhenwei.zscm.common.utils.Linq;
import com.zhenwei.zscm.entity.FileRelationEntity;
import com.zhenwei.zscm.mapper.IFileRelationMapper;
import com.zhenwei.zscm.mappings.FileRelationMapping;
import com.zhenwei.zscm.model.dto.file.FileRelationDTO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@AllArgsConstructor
public class FileRelationRepo extends ServiceImpl<IFileRelationMapper, FileRelationEntity> {
    @Transactional(rollbackFor = Exception.class)
    public boolean saveRelation(String businessId, List<String> fileIdList) {
        List<FileRelationDTO> fileRelationList = Linq.mapList(fileIdList, x -> {
            var dto = new FileRelationDTO();
            dto.setBusinessId(businessId);
            dto.setFileId(x);
            return dto;
        });
        List<FileRelationEntity> entityList = Linq.mapList(fileRelationList, FileRelationMapping.INSTANCE::dto2Entity);
        return this.saveBatch(entityList);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean saveRelation(List<FileRelationDTO> list) {
        List<FileRelationEntity> entityList = Linq.mapList(list, FileRelationMapping.INSTANCE::dto2Entity);
        return this.saveBatch(entityList);
    }

    public List<FileRelationDTO> getFiles(String businessId){
        var q = new LambdaQueryWrapper<FileRelationEntity>()
                .eq(FileRelationEntity::getBusinessId, businessId);
        var list = this.list(q);
        return Linq.mapList(list, FileRelationMapping.INSTANCE::entity2Dto);
    }

    public boolean delete(String businessId) {
        var q = new LambdaQueryWrapper<FileRelationEntity>()
                .eq(FileRelationEntity::getBusinessId, businessId);
        return this.remove(q);
    }

    public List<FileRelationDTO> getUnusedFiles(){
        var q = new LambdaQueryWrapper<FileRelationEntity>()
                .eq(FileRelationEntity::getBusinessId, "");
        var list = this.list(q);
        return Linq.mapList(list, FileRelationMapping.INSTANCE::entity2Dto);
    }
}
